#!/bin/sh
#------------------------------------------------------------------
# Configure OCaml library paths based on information queried from
# ocamlfind & command line and creates a configuration file for
# Ocsigen.
#------------------------------------------------------------------

set -e   # Bail out on errors

site_cma="nurpawiki.cma"
static_root="."
if [ -z $1 ]; then
    true
else
    if [ "$1" = "--godi-install" ]; then
        site_cma=`ocamlfind query nurpawiki`/nurpawiki.cma
        static_root="$LOCALBASE/share/nurpawiki"
    else
        echo Invalid args
        exit 1
    fi
fi

stdlib_path=`ocamlfind ocamlc -where`

str_path=`ocamlfind query str`
nums_path="$stdlib_path"
pcre_path=`ocamlfind query pcre`

calendar_path=`ocamlfind query calendar`
extlib_path=`ocamlfind query extlib`
postgresql_path=`ocamlfind query postgresql`
sqlite3_path=`ocamlfind query sqlite3`
cryptokit_path=`ocamlfind query cryptokit`

ocsigen_libs=`ocamlfind query ocsigen`

if [ "$DEBUG" != "" ]; then
    echo $str_path
    echo $pcre_path
    echo $calendar_path
    echo $extlib_path
    echo $postgresql_path
    echo $sqlite3_path
    echo $ocsigen_libs
fi

mkdir -p var/log
mkdir -p var/run

if [ "$DBNAME" = "" ]; then
    echo
    echo ERROR!
    echo
    echo DBNAME environment variable must be set to point to your nurpawiki DB
    echo
    exit 1
fi

if [ "$DBUSER" = "" ]; then
    echo
    echo ERROR!
    echo
    echo DBUSER environment variable must be set to your nurpawiki DB username
    echo
    exit 1
fi

if [ "$DBPASSWD" = "" ]; then
    echo
    echo ERROR!
    echo
    echo DBPASSWD environment variable must be set to your nurpawiki DB
    echo postgres user password.  See DB installation instructions for
    echo more information on how to configure this.
    echo
    exit 1
fi

cat ocsigen.conf.in | \
    sed -e "s|%_OCSIGEN_ROOT_%|$OCSIGEN_ROOT|g" | \
    sed -e "s|%_STR_CMA_%|${str_path}/str.cma|g" | \
    sed -e "s|%_NUMS_CMA_%|${nums_path}/nums.cma|g" | \
    sed -e "s|%_CALENDAR_CMA_%|${calendar_path}/calendar.cma|g" | \
    sed -e "s|%_PCRE_CMA_%|${pcre_path}/pcre.cma|g" | \
    sed -e "s|%_EXTLIB_CMA_%|${extlib_path}/extLib.cma|g" | \
    sed -e "s|%_POSTGRESQL_CMA_%|${postgresql_path}/postgresql.cma|g" | \
    sed -e "s|%_CRYPTOKIT_CMA_%|${cryptokit_path}/cryptokit.cma|g" | \
    sed -e "s|%_STATIC_ROOT_%|${static_root}|g" | \
    sed -e "s|%_NURPAWIKI_CMA_%|${site_cma}|g" | \
    sed -e "s|%_DBNAME_%|${DBNAME}|g" | \
    sed -e "s|%_DBPASSWD_%|${DBPASSWD}|g" | \
    sed -e "s|%_SQLITE3_CMA_%|${sqlite3_path}/sqlite3.cma|g" | \
    sed -e "s|%_OCSIGEN_MODULES_%|${ocsigen_libs}|g" | \
    sed -e "s|%_DBUSER_%|${DBUSER}|g"
